package com.xtxb.app.rmq.conf;

import com.xtxb.app.rmq.common.Topic;
import com.xtxb.app.rmq.util.FileServer;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.nio.charset.StandardCharsets;
import java.util.*;

@Component
public class MQTopic {
    private Map<String, Topic> topics=new HashMap<>();

    @Autowired
    private FileServer fserver;
    @Autowired
    private MQServer server;

    @PostConstruct
    public void init(){
        Object cache=fserver.loadCache("topic");
        if(cache!=null) {
            topics =(Map)cache;
        }
    }

    public boolean addTopic(Topic topic){
        if(StringUtils.isAnyEmpty(topic.getServerName(),topic.getGroupName(),topic.getTopic())) {
            return false;
        }

        if(server.getServer(topic.getServerName())==null) {
            return false;
        }

        topic.setUuid(Topic.generateUUID(topic));
        if(!topics.containsKey(topic.getUuid())) {
            topics.put(topic.getUuid(),topic);
            fserver.saveCache("topic",topics);
            return true;
        }else{
            return false;
        }
    }

    public boolean deleteTopic(String uuid){
        if(topics.remove(uuid)==null) {
            return false;
        }
        fserver.saveCache("topic",topics);
        return true;
    }

    public Topic getTopic(String uuid){
        return topics.get(uuid);
    }

    public Map<String, Topic> getTopics(){
        return topics;
    }
}
